using System;
using Avalonia.Controls;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using JGSY.AI.DesktopUI.ViewModels;

namespace JGSY.AI.DesktopUI.Views;

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        SetupWindowDragging();
        UpdateMaximizeIcon();

        // Subscribe to window state changes
        this.PropertyChanged += (sender, e) =>
        {
            if (e.Property.Name == nameof(WindowState))
            {
                UpdateMaximizeIcon();
            }
        };
    }

    private void SetupWindowDragging()
    {
        var dragArea = this.FindControl<Grid>("DragArea");
        if (dragArea != null)
        {
            dragArea.PointerPressed += (sender, e) =>
            {
                if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
                {
                    BeginMoveDrag(e);
                }
            };

            // Double click to maximize/restore
            dragArea.DoubleTapped += (sender, e) =>
            {
                if (DataContext is MainWindowViewModel viewModel)
                {
                    viewModel.MaximizeCommand?.Execute(null);
                }
            };
        }
    }

    private void UpdateMaximizeIcon()
    {
        var maximizeIcon = this.FindControl<Path>("MaximizeIcon");
        if (maximizeIcon != null)
        {
            if (WindowState == WindowState.Maximized)
            {
                // Restore icon
                maximizeIcon.Data = Geometry.Parse("M4,8H8V4H20V16H16V20H4V8M16,8V14H18V6H10V8H16M6,12V18H14V12H6Z");
            }
            else
            {
                // Maximize icon
                maximizeIcon.Data = Geometry.Parse("M4,4H20V20H4V4M6,8V18H18V8H6Z");
            }
        }
    }
}
